<template>
  <div class="medicine-container">
    <div class="filter-container">
      <el-input
        v-model="queryParams.name"
        placeholder="请输入药品名称"
        clearable
        style="width: 200px"
        class="filter-item"
        @keyup.enter="handleQuery"
      />
      <el-input
        v-model="queryParams.type"
        placeholder="请输入药品类型"
        clearable
        style="width: 200px"
        class="filter-item"
        @keyup.enter="handleQuery"
      />
      <el-select
        v-model="queryParams.status"
        placeholder="请选择状态"
        clearable
        style="width: 200px"
        class="filter-item"
      >
        <el-option
          v-for="item in statusOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button type="primary" class="filter-item" @click="handleQuery">搜索</el-button>
      <el-button type="success" class="filter-item" @click="handleAdd">添加</el-button>
    </div>

    <el-table v-loading="loading" :data="medicineList" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="药品名称" width="150" />
      <el-table-column prop="type" label="药品类型" width="120" />
      <el-table-column prop="ingredients" label="成分说明" min-width="150" show-overflow-tooltip />
      <el-table-column prop="usageInfo" label="用法用量" min-width="150" show-overflow-tooltip />
      <el-table-column prop="contraindication" label="禁忌" min-width="150" show-overflow-tooltip />
      <el-table-column label="售价" width="100">
        <template #default="scope">
          <span>{{ formatPrice(scope.row.price) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 0 ? 'success' : 'info'">
            {{ scope.row.status === 0 ? '在售' : '停售' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改药品对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="medicineFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="药品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入药品名称" />
        </el-form-item>
        <el-form-item label="药品类型" prop="type">
          <el-input v-model="form.type" placeholder="请输入药品类型/分类" />
        </el-form-item>
        <el-form-item label="成分说明" prop="ingredients">
          <el-input v-model="form.ingredients" type="textarea" placeholder="请输入成分说明" />
        </el-form-item>
        <el-form-item label="用法用量" prop="usageInfo">
          <el-input v-model="form.usageInfo" type="textarea" placeholder="请输入用法用量" />
        </el-form-item>
        <el-form-item label="禁忌" prop="contraindication">
          <el-input v-model="form.contraindication" type="textarea" placeholder="请输入禁忌" />
        </el-form-item>
        <el-form-item label="售价(元)" prop="priceYuan">
          <el-input-number
            v-model="form.priceYuan"
            :precision="2"
            :min="0"
            :step="0.01"
            placeholder="请输入售价"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">在售</el-radio>
            <el-radio :label="1">停售</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listMedicine, getMedicine, addMedicine, updateMedicine, delMedicine } from '@/api/medicine'

// 查询参数
const queryParams = reactive({
  name: '',
  type: '',
  status: undefined
})

// 药品列表数据
const medicineList = ref([])
const loading = ref(false)

// 状态选项
const statusOptions = [
  { value: 0, label: '在售' },
  { value: 1, label: '停售' }
]

// 表单参考
const medicineFormRef = ref()

// 表单数据
const form = reactive({
  id: undefined,
  name: '',
  type: '',
  ingredients: '',
  usageInfo: '',
  contraindication: '',
  price: 0,
  priceYuan: 0,
  status: 0
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '药品名称不能为空', trigger: 'blur' },
    { min: 2, max: 100, message: '药品名称长度必须在2到100个字符之间', trigger: 'blur' }
  ],
  type: [{ required: true, message: '药品类型不能为空', trigger: 'blur' }],
  ingredients: [{ required: true, message: '成分说明不能为空', trigger: 'blur' }],
  usageInfo: [{ required: true, message: '用法用量不能为空', trigger: 'blur' }],
  priceYuan: [{ required: true, message: '售价不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '请选择药品状态', trigger: 'change' }]
}

// 对话框信息
const dialog = reactive({
  visible: false,
  title: '',
  type: ''
})

// 格式化价格显示（分转元）
const formatPrice = (price) => {
  if (price === undefined || price === null) return '0.00'
  return (price / 100).toFixed(2) + ' 元'
}

// 获取药品列表
const getList = async () => {
  loading.value = true
  try {
    const res = await listMedicine(queryParams)
    medicineList.value = res || []
  } catch (error) {
    console.error('获取药品列表失败', error)
    ElMessage.error('获取药品列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  getList()
}

// 重置表单
const resetForm = () => {
  form.id = undefined
  form.name = ''
  form.type = ''
  form.ingredients = ''
  form.usageInfo = ''
  form.contraindication = ''
  form.price = 0
  form.priceYuan = 0
  form.status = 0
  medicineFormRef.value?.resetFields()
}

// 添加按钮操作
const handleAdd = () => {
  resetForm()
  dialog.visible = true
  dialog.title = '添加药品'
  dialog.type = 'add'
}

// 修改按钮操作
const handleUpdate = async (row) => {
  resetForm()
  const id = row.id || row.id
  try {
    const res = await getMedicine(id)
    Object.assign(form, res)
    // 分转元显示
    form.priceYuan = form.price ? form.price / 100 : 0
    dialog.visible = true
    dialog.title = '修改药品'
    dialog.type = 'edit'
  } catch (error) {
    console.error('获取药品详情失败', error)
    ElMessage.error('获取药品详情失败')
  }
}

// 提交表单
const submitForm = async () => {
  medicineFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        // 元转分保存
        form.price = Math.round(form.priceYuan * 100)

        if (form.id) {
          // 修改
          await updateMedicine(form)
          ElMessage.success('修改成功')
        } else {
          // 新增
          await addMedicine(form)
          ElMessage.success('新增成功')
        }
        dialog.visible = false
        getList()
      } catch (error) {
        console.error('提交表单失败', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 删除按钮操作
const handleDelete = (row) => {
  const id = row.id
  ElMessageBox.confirm('确认要删除该药品吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await delMedicine(id)
        getList()
        ElMessage.success('删除成功')
      } catch (error) {
        console.error('删除药品失败', error)
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.medicine-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-item {
  margin-right: 10px;
}

.dialog-footer {
  text-align: right;
}
</style>
